import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import { Card, Row, Col, DatePicker, Form,Button,Table, Spin} from 'antd';
import HeaderTab from '@/components/HeaderTab'
import styles from './index.less'
import moment from  'moment';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;

@Form.create()
class Pagination extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      btnLoading: false,
      loading: true,
      dataSource:[],
      paginationProps: {
        showSizeChanger: true,
        showQuickJumper: false,
        showTotal: total => `共 ${total} 条记录`,
        pageSize: 10,
        total: 0,
        pageIndex: 1,
      },
      tabs: [{
        title: '手机短信',
        key: `/${window.storeId}/sms`,
      }, {
        title: '充值记录',
        key:  `/${window.storeId}/sms/buyrecord`
      },{
        title: '短信签名',
        key:  `/${window.storeId}/sms/sign`
      }]
    };
  }
  componentWillMount(){
    this.getSmsRechargeRecordListWithPage();
    window.Isoption = false;
  }

  componentDidMount() {
    window.Isoption = true;
  }

  getSmsRechargeRecordListWithPage =params => {
    const { dispatch} = this.props;
    const { paginationProps: { pageIndex, pageSize } } = this.state;
    dispatch({
      type: 'stortMessage/GetSmsRechargeRecordListWithPage',
      payload: {
        PageIndex: pageIndex, //页码
        PageSize: pageSize, //页数
        StartDate: params && params.StartDate? params.StartDate: null,
        EndDate: params && params.EndDate? params.EndDate: null,
      },
      callBack: {
        success: res => {
          if(res.Code ===0) {
            this.setState({
              paginationProps: {
                ...this.state.paginationProps,
                total: res.Data.Total
              },
              dataSource: res.Data?res.Data.DataList: [],
              btnLoading: false,
              loading: false
            })
          }
        },
        error: res => {
          console.log(res)
        }
      }
    })
  }

  onChange = (data)=> {
    this.setState({
      current: data.current,
      pageSize: data.pageSize,
    });
  }
  onTabChange=(id)=> {
    this.setState({
      activeId: id
    },()=>{
        router.replace({
            pathname: `${id}`
        })
    });
  }

  // 重置
handleFormReset =() => {
    const { form } = this.props;
    form.resetFields();
}

handleSearch =e => {
  e.preventDefault();
  const {form} = this.props;
  this.setState({
    btnLoading: true
  })
  form.validateFields((err, values) => {
    if(!err) {
      const datas = {
        StartDate:values.Date && values.Date[0]?moment(values.Date[0]).format('YYYY-MM-DD'):'',
        EndDate:values.Date && values.Date[1]?moment(values.Date[1]).format('YYYY-MM-DD'):'',
    };
    this.setState({
      formValues: datas
    })
    this.getSmsRechargeRecordListWithPage({...datas});
    }
  })
}

//table切换
onTableChange =(pagination, filters, sorter) => {
  // console.log(pagination, filters, sorter)
    let {paginationProps} = this.state;
    let data = {
        ...paginationProps,
        pageIndex: pagination.current,
        pageSize: pagination.pageSize,
    };
    this.setState({
      paginationProps: data
    }, () => {
        this.getSmsRechargeRecordListWithPage()
    })
}

  renderForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    const {btnLoading} = this.state;

    return (
        <Form layout="inline" onSubmit={this.handleSearch}>
            <Row>
            <Col span={8}>
                <FormItem label="充值时间">
                {getFieldDecorator('Date')(
                    <RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} />
                )}
                </FormItem>
            </Col>
            </Row>
            <div style={{ overflow: 'hidden' }}>
                <div className="screenNavButton">
                    <Button type="primary" htmlType="submit" loading={btnLoading}>
                        筛选
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                        重置
                    </Button>
                </div>
            </div>
        </Form>
    )
  }

  render() {
      const columns = [
        {
            title: '充值时间',
            dataIndex: 'CreateTime',
            key: 'CreateTime',
        },
        {
            title: '充值前可用数量（条）',
            dataIndex: 'BeforeNumber',
            key: 'BeforeNumber',
            align: 'right'
        },
        {
            title: '充值数量（条）',
            dataIndex: 'Number',
            key: 'Number',
            align: 'right'
        },
        {
            title: '充值后可用数量（条）',
            dataIndex: 'AfterNumber',
            key: 'AfterNumber',
            align: 'right'
        },
        {
            title: '充值方式',
            dataIndex: 'RechargeTypeName',
            key: 'RechargeTypeName',
        },
        {
            title: '充值金额',
            dataIndex: 'RechargeFee',
            key: 'RechargeFee',
            align: 'right'
        },
      ]
      const {dataSource, loading} = this.state;
      const {loading1} = this.props;
    return (
        <Fragment>
        
          <Spin spinning={loading}>
            <Card bordered={false} className={styles.cardContent}>
                  <div style={{
                          height:112,
                          background:'#fafafa',
                          marginBottom:16,
                          paddingTop:16,
                          paddingRight:16,
                          boxSizing:'border-box',
                          marginTop: 16
                      }}>
                      <div className="tableListForm">{this.renderForm()}</div>
                  </div>
                  <Spin spinning={loading1}>
                      <Table
                          columns={columns}
                          dataSource ={dataSource?dataSource:[]}
                          rowKey={record => record.Id}
                          onChange={this.onTableChange}
                          pagination={this.state.paginationProps}
                      />
                  </Spin>
              </Card>
          </Spin>
        </Fragment>
    );
  }
}


export default connect(({ stortMessage,global, loading }) => ({
      stortMessage,
      loading1: loading.effects['stortMessage/GetSmsRechargeRecordListWithPage'],
  }))(Pagination)
